﻿using HZH_Controls.Controls;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using 渐变.customercolumn;
using 渐变.model;

namespace 渐变.admin_Form
{
    public partial class admin_carManager : Form
    {
        public admin_carManager()
        {
            InitializeComponent();
        }

        private void admin_carManager_Load(object sender, EventArgs e)
        {
            this.Dock = DockStyle.Fill;
        }

        public void loadSearchType()
        {
            string sql = "select * from CarTypeInfo where CIsDelete = 0";
            DataTable dt = new DataTable();
            dt = DBHelper.ExecuteQuery(sql);
            DataRow dr = dt.NewRow();
            dr[0] = 0;
            dr[1] = "全部分类";
            dr[2] = 0;
            dt.Rows.InsertAt(dr, 0);
            cmbSearchType.DataSource = dt;
            cmbSearchType.DisplayMember = "CTitle";
            cmbSearchType.ValueMember = "CTypeId";
            cmbSearchType.SelectedIndex = 0;
        }
        private void cardata_Load(object sender, EventArgs e)
        {
            loadSearchType();
            InitDataGridViewHeader();
            var countsql = new StringBuilder();
            countsql.Append($"Select COUNT(ci.CId)");
            countsql.Append(Environment.NewLine);
            countsql.Append($"From CarInfo as ci");
            countsql.Append(Environment.NewLine);
            countsql.Append($"LEFT JOIN CarTypeInfo as cti ON ci.CTypeId = cti.CTypeId");
            countsql.Append(Environment.NewLine);
            countsql.Append($"WHERE ci.CIsDelete = 0");

            int count = (int)DBHelper.ExecuteScalar(countsql.ToString());

            var ds = new List<object>();
            if (count > 0)
            {
                for (int i = 0; i < count; i++)
                {
                    ds.Add(i);
                }
            }
            this.pc1.DataSource = ds;
            this.pc1.PageSize = 10;
            this.pc1.StartIndex = 0;
            this.pc1.FirstPage();
            this.pc1.PageCount = count / 10 + (count % 10 > 0 ? 1 : 0);
            this.pc1.ShowSourceChanged += pc1_ShowSourceChanged;


            var sql = new StringBuilder();
            sql.Append($"Select top 10 temp.CId, temp.CName,temp.CName,temp.CPrice,temp.CImg,temp.CNumber,temp.CTypeId,temp.CStatus,temp.CTitle");
            sql.Append(Environment.NewLine);
            sql.Append($"from (select row_number() over(order by CID asc) as rownumber,CId,CName,CPrice,CImg,CNumber,ci.CTypeId,CStatus,CTitle From CarInfo as ci");
            sql.Append(Environment.NewLine);
            sql.Append($"LEFT JOIN CarTypeInfo as cti ON ci.CTypeId = cti.CTypeId WHERE ci.CIsDelete = 0) as temp");
            sql.Append(Environment.NewLine);
            sql.Append($"WHERE rownumber > 0;");

            //            select top 10 *
            //from(select row_number()
            //over(order by sno asc) as rownumber, *
            //from student) temp_row
            //where rownumber > 10;

            DataTable dt = new DataTable();
            dt = DBHelper.ExecuteQuery(sql.ToString());
            this.cardata.DataSource = dt;
            this.cardata.First();
        }
        private void InitDataGridViewHeader()
        {
            List<DataGridViewColumnEntity> lstCulumns = new List<DataGridViewColumnEntity>();
            lstCulumns.Add(new DataGridViewColumnEntity() { DataField = "CId", HeadText = "id", Width = 80, WidthType = SizeType.Absolute });
            lstCulumns.Add(new DataGridViewColumnEntity() { DataField = "CName", HeadText = "车名", Width = 120, WidthType = SizeType.Absolute });
            lstCulumns.Add(new DataGridViewColumnEntity() { DataField = "CPrice", HeadText = "日租价格", Width = 120, WidthType = SizeType.Absolute });
            //lstCulumns.Add(new DataGridViewColumnEntity() { DataField = "CImg", HeadText = "图片", Width = 20, WidthType = SizeType.Percent });
            lstCulumns.Add(new DataGridViewColumnEntity() { DataField = "CNumber", HeadText = "车牌号", Width = 150, WidthType = SizeType.Absolute });
            lstCulumns.Add(new DataGridViewColumnEntity() { DataField = "CStatus", HeadText = "状态", Width = 150, WidthType = SizeType.Absolute, Format = (a) => { return (bool)a ? "启用" : "停用"; } });
            lstCulumns.Add(new DataGridViewColumnEntity() { DataField = "CTitle", HeadText = "类型", Width = 150, WidthType = SizeType.Absolute });
            lstCulumns.Add(new DataGridViewColumnEntity() { HeadText = "图片", Width = 50, WidthType = SizeType.Absolute, CustomCellType = typeof(GridImageCell) });
            this.cardata.Columns = lstCulumns;
            this.cardata.IsShowCheckBox = true;
            List<object> lstSource = new List<object>();
        }

        /*搜索功能 start*/
        public void loadSearch()
        {
            string sql = "select CId,CName,CPrice,CImg,CNumber,CarInfo.CTypeId,CStatus,CarTypeInfo.CTypeId,CTitle from CarInfo,CarTypeInfo where CarInfo.CTypeId=CarTypeInfo.CTypeId and CarInfo.CIsDelete=0 and CTitle=@ctitle";
            SqlParameter type = new SqlParameter("@ctitle", cmbSearchType.Text);
            if (cmbSearchType.Text == "全部分类")
            {
               cardata_Load(null, null);
            }
            else
            {
                DataTable dt = new DataTable();
                dt = DBHelper.ExecuteQuery(sql, type);
                //cardata.AutoGenerateColumns = false;
                cardata.DataSource = dt;
            }
        }
        /*搜索功能 end*/

        private void pc1_ShowSourceChanged(object currentSource)
        {
            var list = this.pc1.GetCurrentSource();
            if (list != null && list.Count > 0)
            {

                var sql = new StringBuilder();
                sql.Append($"Select top 10 temp.CId, temp.CName,temp.CName,temp.CPrice,temp.CImg,temp.CNumber,temp.CTypeId,temp.CStatus,temp.CTitle");
                sql.Append(Environment.NewLine);
                sql.Append($"from (select row_number() over(order by CID asc) as rownumber,CId,CName,CPrice,CImg,CNumber,ci.CTypeId,CStatus,CTitle From CarInfo as ci");
                sql.Append(Environment.NewLine);
                sql.Append($"LEFT JOIN CarTypeInfo as cti ON ci.CTypeId = cti.CTypeId WHERE ci.CIsDelete = 0) as temp");
                sql.Append(Environment.NewLine);
                sql.Append($"WHERE rownumber > {10 * ((int)list[0] / 10)};");

                DataTable dt = new DataTable();
                dt = DBHelper.ExecuteQuery(sql.ToString());
                InitDataGridViewHeader();
                this.cardata.DataSource = dt;
            }
            else
            {
                this.cardata.DataSource = null;
            }
        }

        /*增加车辆按钮    start*/
        private void btnAddCar_Click(object sender, EventArgs e)
        {
            addCarForm addCarForm = new addCarForm();
            DialogResult dr = addCarForm.ShowDialog();
            if (dr == DialogResult.OK)
            {
                cardata_Load(null, null);
            }
        }
        /*增加车辆按钮    end*/

        /*车辆的批量删除  start*/
        private void btnDeleteCar_Click(object sender, EventArgs e)
        {
            if (cardata.SelectRows != null && cardata.SelectRows.Count > 0)
            {
                var uids = new List<int>();
                foreach (var item in cardata.SelectRows)
                {
                    var tempid = Convert.ToInt32((item.DataSource as DataRow)["CId"]);
                    uids.Add(tempid);
                }
                DialogResult dir = MessageBox.Show("您确定要删除该用户吗？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
                if (dir == DialogResult.OK)
                {
                    var uidsstr = new StringBuilder();
                    uidsstr.Append("(");
                    foreach (var item in uids)
                    {
                        uidsstr.Append($"{item},");
                    }
                    uidsstr.Remove(uidsstr.Length - 1, 1);
                    uidsstr.Append(")");
                    string sql = $"delete from CarInfo where CId IN {uidsstr};";
                    int result = DBHelper.ExecuteNonQuery(sql);
                    if (result > 0)
                    {
                        this.ShowSuccessTip("删除成功！");
                        cardata_Load(null, null);
                    }
                    else
                    {
                        this.ShowErrorTip("删除失败！");
                    }
                }
                else
                {
                    return;
                }
            }
            else
            {
                this.ShowErrorTip("未选择任何车辆，请选择要删除的车辆再进行删除!");
            }
        }
        /*车辆的批量删除  end*/


        /*控制按钮的可用   start*/
        private void cardata_ItemClick(object sender, DataGridViewEventArgs e)
        {

            var rows = cardata.SelectRows;
            if (rows != null && rows.Count > 0)
            {
                btnEditCar.Enabled = true;
            }
            else
            {
                btnEditCar.Enabled = false;
            }
        }
        /*控制按钮的可用   end*/

        private void btnEditCar_Click(object sender, EventArgs e)
        {
            int CId = Convert.ToInt32((cardata.SelectRow.DataSource as DataRow)["CId"]);
            string CName = (cardata.SelectRow.DataSource as DataRow)["CName"].ToString();
            decimal CPrice = Convert.ToDecimal((cardata.SelectRow.DataSource as DataRow)["CPrice"]);
            string CImg = (cardata.SelectRow.DataSource as DataRow)["CImg"].ToString();
            string CTitle = (cardata.SelectRow.DataSource as DataRow)["CTitle"].ToString();
            string CNumber = (cardata.SelectRow.DataSource as DataRow)["CNumber"].ToString();
            bool CStatus = Convert.ToBoolean((cardata.SelectRow.DataSource as DataRow)["CStatus"]);
            
            editCarForm editCarForm = new editCarForm(new carInfo()
            {
                CId = CId,
                CName = CName,
                CPrice = CPrice,
                CImg = CImg,
                //CTitle = CTitle,
                CNumber = CNumber,
                CStatus = CStatus

            });
            editCarForm.CTitleValue = CTitle;
            DialogResult dir = editCarForm.ShowDialog();
            //OpenFileDialog fileDialog = new OpenFileDialog();
            /* rentCarForm.Show();*/
            if (dir == DialogResult.OK)
            {
                //loadMsg();
                cardata_Load(null, null);
            }
        }

        private void cmbSearchType_TextChanged(object sender, EventArgs e)
        {
            loadSearch();
        }
    }
}
